package model

import (
	"../global"
	"github.com/go-pg/pg"
)

type ItemModel struct {
}

//新增产品
func (*ItemModel) CreateItem(query *Item) (err error) {
	_, err = global.DB.Model(query).Insert()
	return
}

//获取产品
func (*ItemModel) GetItem(query *Item, column []string, listParams *ListParams) (result []Item, err error) {
	model := global.DB.Model(&result)
	for k := range column {
		model.Column(column[k])
	}
	if query.ID != 0 {
		model.Where("id=?", query.ID)
	}
	if query.Name != "" {
		model.Where("name=?", query.Name)
	}

	if query.Hot == true {
		model.Where("hot=?", true)
	}
	if query.AllowShow == true {
		model.Where("allow_show=?", true)
	}
	if query.AllowPay == true {
		model.Where("allow_pay", true)
	}
	if query.Deleted == true {
		model.Where("deleted", true)
	}

	if listParams.Limit != 0 && listParams.Page != 0 {
		err = model.Limit(listParams.Limit).Offset((listParams.Page - 1) * listParams.Limit).Select()
	} else {
		err = model.Limit(listParams.Limit).Select()
	}
	return
}

//修改产品
func (*ItemModel) EditItem(query *Item) (err error) {
	model := global.DB.Model(&Item{})
	model.Where("id=?", query.ID)

	if query.Name != "" {
		model.Set("name=?", query.Name)
	}
	if query.SortID != 0 {
		model.Set("sort_id=?", query.SortID)
	}
	if query.Deleted == true {
		model.Set("deleted=?", true)
	}
	if query.Hot == true {
		model.Set("hot=?", true)
	}
	if query.Scale != 0 {
		model.Set("scale=?", query.Scale)
	}
	if query.Source != "" {
		model.Set("source=?", query.Source)
	}
	if query.SourceUrl != "" {
		model.Set("source_url=?", query.SourceUrl)
	}
	if query.Level1ProfitRate != 0 {
		model.Set("level1_profit_rate=?", query.Level1ProfitRate)
	}
	if query.Level1PriceRate != 0 {
		model.Set("level1_price_rate=?", query.Level1PriceRate)
	}
	if query.Level2ProfitRate != 0 {
		model.Set("level2_profit_rate=?", query.Level2ProfitRate)
	}
	if query.Level2PriceRate != 0 {
		model.Set("level2_price_rate=?", query.Level2PriceRate)
	}
	if query.Level3ProfitRate != 0 {
		model.Set("level3_profit_rate=?", query.Level3ProfitRate)
	}
	if query.Level3PriceRate != 0 {
		model.Set("level3_price_rate=?", query.Level3PriceRate)
	}
	_, err = model.Update()
	return
}

//删除产品
func (*ItemModel) DelItem(IDs []int64) (err error) {
	if len(IDs) > 1 {
		_, err = global.DB.Model(&Item{}).WhereIn("id IN (?)", pg.In(IDs)).Delete()
	} else {
		_, err = global.DB.Model(&Item{}).Where("id=?", IDs[0]).Delete()
	}
	return
}
